package GUI;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.Toolkit;

import javax.swing.AbstractButton;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

import java.awt.Font;
import java.io.IOException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;

import javax.swing.JLabel;
import javax.swing.border.TitledBorder;

import jpos.JposException;
import jpos.POSPrinter;
import jpos.POSPrinterConst;

import CommonGui.ManagePrinter;
import DataObjects.Bon;
import DataObjects.Menu;
import DataObjects.MessageGetDetailsDiscountOfTableReply;
import DataObjects.MetaDataOrder;
import DataObjects.Payment;
import Messages.MessageAddNewPaymentOfTable;
import Messages.MessageAddRecipeToDataBase;
import Messages.MessageCheckBalancePresentCard;
import Messages.MessageCheckBalancePresentCardReply;
import Messages.MessageCheckExistPresentCard;
import Messages.MessageCheckExistPresentCardReply;
import Messages.MessageCloseTable;
import Messages.MessageGetAllMenues;
import Messages.MessageGetAllMenuesReply;
import Messages.MessageGetDetailsDiscountOfTable;
import Messages.MessageGetPaymentDetailsByOrderID;
import Messages.MessageGetPaymentDetailsByOrderIDReply;
import Messages.MessageSavingReply;

public class PfPointOfSale extends JPanel{
	
	private MainMenu mainMenu;
	private Dimension screenSize;
	private int x;
	private int y;
	private int xx;
	private int yy;
	private int xxheight;
	private int yywidth;
	
	public JPanel leftPanel;
	public JPanel leftChangePanel;
	public JPanel rightPanel;
	public JPanel rightSecondPanel;
	public JPanel rightSecondPresentPanel;
	public JPanel textFieldPanel;
	public JPanel rightSecondDiscountPanel;
	
	private JButton btnIsracart;
	private JButton btnPresentCard;
	private JButton btnOtherPaymentWay;
	private JButton btnCashFlow;
	private JButton backButt;
	private JButton btnDiscount;
	private JButton cancelButt;
	private JButton payButt;
	
	private Vector<Menu> menues;
	private Vector<Bon> bones;
	private MetaDataOrder metaDataOrder;
	private Vector<Payment> wasPaidAlready;  
	private Vector<String> discountTable=null;
	
	public Float totalPrice = (float) 0.0;
	public Float totalPriceWithoutNDS =  (float) 0.0;
	public Float totalNDS=  (float) 0.0;
	public Float wasPaid=  (float) 0.0;                          //summa kotoruyu uje zaplatili(ona ne obyazana bit ravna toi kotoruyu doljni zaplatit)
	public Float totalPriceWithNDSAfterDiscount=  (float) 0.0;
	private Float balance;
	
	public JLabel lblTotalCostWithoutNDS;
	
    public JTextField flowTextField;
	
	
	
	public PfPointOfSale(MainMenu mm,Vector<Bon> bon,MetaDataOrder metaDataOrder)
	{
		
		super();
		setBackground(Color.WHITE);
		this.bones=bon;
		this.mainMenu=mm;
		this.metaDataOrder=metaDataOrder;
		screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		x=screenSize.width;
		y=screenSize.height;
		System.out.println("x"+x);
		System.out.println("y"+y);
		this.setLayout(null);
			
		initialize();
		
		
	}

	private void initialize()
	{
		this.add(getRightPanel(this,bones));
		calculatePricesForLefrPanel();
	
	}
	
	
	public void calculatePricesForLefrPanel()
	{
		int i;
		int j;
		totalPrice = (float) 0.0;
		totalPriceWithoutNDS =  (float) 0.0;
		totalNDS=  (float) 0.0;
		wasPaid=  (float) 0.0;  
	    totalPriceWithNDSAfterDiscount=  (float) 0.0;
		wasPaidAlready = new Vector<Payment>();
		discountTable = new Vector<String>();
		
		MessageGetPaymentDetailsByOrderID msgGetPaymentDetails= new MessageGetPaymentDetailsByOrderID(Integer.parseInt(metaDataOrder.getOrderId()));
				try {
					mainMenu.ms.client.sendToServer(msgGetPaymentDetails);
		            MessageGetPaymentDetailsByOrderIDReply result = (MessageGetPaymentDetailsByOrderIDReply)mainMenu.ms.client.GetMessage();
				    wasPaidAlready=result.getPay();
					}
							 catch (IOException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								                    }
				
		MessageGetDetailsDiscountOfTable msgGetDiscountDetails=new MessageGetDetailsDiscountOfTable(metaDataOrder.getOrderId());
		try {
				mainMenu.ms.client.sendToServer(msgGetDiscountDetails);
				MessageGetDetailsDiscountOfTableReply result1 = (MessageGetDetailsDiscountOfTableReply)mainMenu.ms.client.GetMessage();
					if(result1.getDetails().isEmpty())
					 {}
						else
						{
							discountTable=result1.getDetails();
						}
			}
					 catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						                    }
		for(j=0;j<wasPaidAlready.size();j++)
		{
			wasPaid=(wasPaid+wasPaidAlready.get(j).getAmount());
			btnDiscount.setEnabled(false);
		}
				
					
		
			for(i=0;i<bones.size();i++)
			{
				totalPriceWithoutNDS=Float.parseFloat(bones.get(i).getPrice())+totalPriceWithoutNDS;
				totalPrice=totalPriceWithoutNDS;
			}
		            
							            
					if(discountTable.isEmpty())
					{
						totalPriceWithoutNDS=totalPriceWithoutNDS-wasPaid;
						System.out.println("totalPriceWithoutNDS"+totalPriceWithoutNDS);
						System.out.println("wasPaid"+wasPaid);
						totalPrice=totalPriceWithoutNDS;
						if(totalPriceWithoutNDS<=0)
						{
							
							if(leftPanel!=null)
							{
								this.remove(leftPanel);
								
							}
								this.add(getLeftChangePanel());
								this.repaint();
								
								System.out.println("pered if");
								/*if(this.mainMenu.getjPos_Printer()==null)
								{
									System.out.println("vnutri if");
									ManagePrinter managePrinter=new ManagePrinter();
									mainMenu.setManagePrinter(managePrinter);
									mainMenu.setjPos_Printer(managePrinter.getjPos_Printer());
									mainMenu.setCashDrawer(managePrinter.getCashDrawer());
									
								}
								InitFram();
								try {
									mainMenu.getCashDrawer().openDrawer();
								} catch (JposException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}*/
								
								
								return;
						}
					}
					else
					{
						System.out.println("discount");
						totalPriceWithNDSAfterDiscount=totalPriceWithoutNDS;
						if(discountTable.get(2).equals("%"))
						{
					     float temp=(100-(Float.parseFloat(discountTable.get(1))))/100;
							totalPriceWithNDSAfterDiscount= (float)((totalPriceWithNDSAfterDiscount*temp)-wasPaid);
							totalPrice=(float)totalPriceWithNDSAfterDiscount/temp;
						}
						else
						{
							totalPriceWithNDSAfterDiscount= (float)((totalPriceWithNDSAfterDiscount-Float.parseFloat(discountTable.get(1))-wasPaid));
							totalPrice=(float)totalPriceWithNDSAfterDiscount+Float.parseFloat(discountTable.get(1));
						}
						if(totalPriceWithNDSAfterDiscount<=0)
						{
							
							if(leftPanel!=null)
							{
								this.remove(leftPanel);
								
							}
							    System.out.println("pered if");
								this.add(getLeftChangePanel());
								this.repaint();
								/*System.out.println("pered if");
								if(this.mainMenu.getjPos_Printer()==null)
								{
									System.out.println("vnutri if");
									ManagePrinter managePrinter=new ManagePrinter();
									mainMenu.setManagePrinter(managePrinter);
									mainMenu.setjPos_Printer(managePrinter.getjPos_Printer());
									mainMenu.setCashDrawer(managePrinter.getCashDrawer());
									
								}
								InitFram();
								try {
									mainMenu.getCashDrawer().openDrawer();
								} catch (JposException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}*/
								return;
						}
						
						
				
					}
						
					
							totalPriceWithoutNDS=(float) (totalPrice/1.15);
							totalPriceWithoutNDS =Float.parseFloat((new DecimalFormat("##.#").format(totalPriceWithoutNDS)));
							totalNDS=totalPrice-totalPriceWithoutNDS;
							totalNDS=Float.parseFloat((new DecimalFormat("##.#").format(totalNDS)));
		
									if(leftPanel!=null)
										this.remove(leftPanel);
										this.add(getLeftPanel( wasPaid,discountTable));
									    this.repaint();
								}
	
	
	
	public JPanel getLeftChangePanel()
	{
		
		leftChangePanel = new JPanel();
		leftChangePanel.setBackground(new Color(250, 235, 215));
		leftChangePanel.setLayout(null);
		leftChangePanel.setBorder(new TitledBorder(null, "סיכום כספי", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		leftChangePanel.setBounds(x/126, y/73, x*20/48, y*10/13);
		
		leftChangePanel.add(getBackButton());
		
		if(wasPaidAlready.get(wasPaidAlready.size()-1).getChange()!=(float)0)
		{
			
		JLabel label = new JLabel("עודף:");
		label.setFont(new Font("Tahoma", Font.PLAIN, x/62));
		label.setBounds(x*10/42, y/12, x/10, y/22);
		leftChangePanel.add(label);
		
		JLabel  lblchange = new JLabel();
	    lblchange.setFont(new Font("Tahoma", Font.PLAIN, x/62));
	    
	    lblchange.setText(  Float.toString(wasPaidAlready.get(wasPaidAlready.size()-1).getChange())   );
	    lblchange.setBounds(x/10, y/12, x/15, y/22);
	    leftChangePanel.add(lblchange);
		}
		else
		{
			
			JLabel label = new JLabel("טיף:");
			label.setFont(new Font("Tahoma", Font.PLAIN, x/62));
			label.setBounds(x*10/42, y/12, x/10, y/22);
			leftChangePanel.add(label);
			
			JLabel  lblchange = new JLabel();
		    lblchange.setFont(new Font("Tahoma", Font.PLAIN, x/62));
		    lblchange.setText(  Float.toString(wasPaidAlready.get(wasPaidAlready.size()-1).getTips())   );
		    lblchange.setBounds(x/10, y/12, x/15, y/22);
		    leftChangePanel.add(lblchange);
		   
		}
	    
	    Date dat = new Date();
	    DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
		DateFormat df1 = new SimpleDateFormat("HH:mm:ss");
		 
		  String   data = df.format(dat);
		  String   time = df1.format(dat);
		  metaDataOrder.setDateClose(data) ;
		  metaDataOrder.setTimeClose(time) ;
	    MessageCloseTable msgCloseTable = new MessageCloseTable(bones,metaDataOrder);
	    try {
			mainMenu.ms.client.sendToServer(msgCloseTable);
			
			MessageSavingReply result = (MessageSavingReply)mainMenu.ms.client.GetMessage();
				if (result.getResult()== '0')
		    	{
		    		JOptionPane.showMessageDialog(null,"בעיית תקשורת 03");
		    	}
	    	} catch (IOException e) {
			
			e.printStackTrace();
		}
	    
				    btnCashFlow.setEnabled(false);
				    btnIsracart.setEnabled(false);
				    btnPresentCard.setEnabled(false);
					btnOtherPaymentWay.setEnabled(false);
					btnDiscount.setEnabled(false);
				
		return leftChangePanel;
	}
	
	
	public JPanel getLeftPanel(Float wasPaid,Vector<String> detailsDiscount)
	{
			
		leftPanel = new JPanel();
		leftPanel.setBackground(new Color(250, 235, 215));
		leftPanel.setLayout(null);
		leftPanel.setBorder(new TitledBorder(null, "סיכום כספי", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		leftPanel.setBounds(x/126, y/73, x*20/48, y*10/13);
		
		leftPanel.add(getBackButton());
		if(wasPaid!=0.0)
			backButt.setEnabled(false);
	
			
		JLabel label = new JLabel("סיכום ביניים:");
		label.setFont(new Font("Tahoma", Font.PLAIN, x/62));
		label.setBounds(x*10/42, y/12, x/10, y/22);
		leftPanel.add(label);
		
	    lblTotalCostWithoutNDS = new JLabel();
		lblTotalCostWithoutNDS.setFont(new Font("Tahoma", Font.PLAIN, x/62));
		lblTotalCostWithoutNDS.setText(Float.toString(totalPriceWithoutNDS));
		lblTotalCostWithoutNDS.setBounds(x/10, y/12, x/15, y/22);
		leftPanel.add(lblTotalCostWithoutNDS);
		
		JLabel labelNDS = new JLabel("מע\"מ:");
		labelNDS.setFont(new Font("Tahoma", Font.PLAIN, x/62));
		labelNDS.setBounds(x*10/42, y/5, x/10, y/22);
		leftPanel.add(labelNDS);
		
				
		JLabel labelCostNDS = new JLabel();
		labelCostNDS.setText(Float.toString(totalNDS));
		labelCostNDS.setFont(new Font("Tahoma", Font.PLAIN, x/62));
		labelCostNDS.setBounds(x/10, y/5, x/15, y/22);
		leftPanel.add(labelCostNDS);
		
		JSeparator separ = new JSeparator(SwingConstants.HORIZONTAL);
		
		separ.setBounds(x/10,  y*10/26, x/15, y/32);
		leftPanel.add(separ);
		
		
		JLabel labelCostWithNDS = new JLabel(" סה''כ לפני ההנחה:");
		labelCostWithNDS.setFont(new Font("Tahoma", Font.PLAIN, x/62));
		labelCostWithNDS.setBounds(x*10/42, y*10/32, x/6, y/22);
		leftPanel.add(labelCostWithNDS);
		
		JLabel labelAmountCostWithNDS = new JLabel();
		labelAmountCostWithNDS.setText(Float.toString(totalPrice));
		labelAmountCostWithNDS.setFont(new Font("Tahoma", Font.BOLD, x/60));
		labelAmountCostWithNDS.setBounds(x/10, y*10/32, x/15, y/22);
		leftPanel.add(labelAmountCostWithNDS);
		
		if(detailsDiscount.isEmpty())
		{
			JLabel labelDiscount = new JLabel("הנחה:");
			labelDiscount.setFont(new Font("Tahoma", Font.PLAIN, x/62));
			labelDiscount.setBounds(x*10/42, y*10/24, x/10, y/22);
			leftPanel.add(labelDiscount);
			
			JLabel labelAmountDiscount = new JLabel();
			labelAmountDiscount.setText("0");
			labelAmountDiscount.setFont(new Font("Tahoma", Font.PLAIN, x/62));
			labelAmountDiscount.setBounds(x/10, y*10/24, x/15, y/22);
			leftPanel.add(labelAmountDiscount);
			
			/*JSeparator separ1 = new JSeparator(SwingConstants.HORIZONTAL);
			separ1.setBounds(x/10, y*10/22, x/10, y/32);
			leftPanel.add(separ1);*/
			
			JSeparator separ2 = new JSeparator(SwingConstants.HORIZONTAL);
			separ2.setBounds(x/10,  y*10/21, x/5, y/32);
			separ2.setBackground(Color.black);
			leftPanel.add(separ2);
			
			
			JLabel labelTotalAfter = new JLabel("סה''כ לחיוב:");
			labelTotalAfter.setFont(new Font("Tahoma", Font.PLAIN, x/62));
			labelTotalAfter.setBounds(x*10/42, y*10/19, x/8, y/22);
			leftPanel.add(labelTotalAfter);
			
			JLabel labelAmountTotalAfter = new JLabel();
			labelAmountTotalAfter.setText(Float.toString(totalPrice));
			labelAmountTotalAfter.setFont(new Font("Tahoma", Font.BOLD, x/60));
			labelAmountTotalAfter.setBounds(x/10,  y*10/19, x/15, y/22);
			leftPanel.add(labelAmountTotalAfter);
		}
		else
		{
			
		JLabel labelDiscount = new JLabel("הנחה:");
		labelDiscount.setFont(new Font("Tahoma", Font.PLAIN, x/62));
		labelDiscount.setBounds(x*10/42, y*10/24, x/10, y/22);
		leftPanel.add(labelDiscount);
		
		JLabel labelAmountDiscount = new JLabel();
		labelAmountDiscount.setText(detailsDiscount.get(1)+detailsDiscount.get(2));
		labelAmountDiscount.setFont(new Font("Tahoma", Font.PLAIN, x/62));
		labelAmountDiscount.setBounds(x/10, y*10/24, x/15, y/22);
		leftPanel.add(labelAmountDiscount);
		
		JSeparator separ2 = new JSeparator(SwingConstants.HORIZONTAL);
		separ2.setBounds(x/10,  y*10/21, x/5, y/32);
		separ2.setBackground(Color.black);
		leftPanel.add(separ2);
		
		JLabel labelTotalAfter = new JLabel("סה''כ לחיוב:");
		labelTotalAfter.setFont(new Font("Tahoma", Font.PLAIN, x/62));
		labelTotalAfter.setBounds(x*10/42, y*10/19, x/10, y/22);
		leftPanel.add(labelTotalAfter);
		
		JLabel labelAmountTotalAfter = new JLabel();
		if(detailsDiscount.get(2).equals("%"))
		{
		    labelAmountTotalAfter.setText(Float.toString(totalPriceWithNDSAfterDiscount));
		}
		else
		{
			labelAmountTotalAfter.setText(Float.toString(totalPrice-Float.parseFloat(detailsDiscount.get(1))));
			totalPrice=totalPrice-Float.parseFloat(detailsDiscount.get(1));
		}
		labelAmountTotalAfter.setFont(new Font("Tahoma", Font.BOLD, x/60));
		labelAmountTotalAfter.setBounds(x/10,  y*10/19, x/15, y/22);
		leftPanel.add(labelAmountTotalAfter);
		
		}
			
		return leftPanel;
	}
	
	
	private JButton getBackButton()
	{
		Icon backIcon = new ImageIcon("back-icon.png");
		Image img = ((ImageIcon) backIcon).getImage();
		Image newimg = img.getScaledInstance(40, 40,java.awt.Image.SCALE_SMOOTH);
		backIcon = new ImageIcon(newimg);
	    backButt=new JButton("לרשימת שולחנות",backIcon);
		//backButt.setBackground(new Color(0, 255, 255)); 
		backButt.setBackground(new Color(200,250,230));
		backButt.setVerticalTextPosition(AbstractButton.BOTTOM);
		backButt.setHorizontalTextPosition(AbstractButton.CENTER);
		backButt.setFont(new Font("Tahoma", Font.BOLD, x/90));
		backButt.setBounds(9*x/500, 15*y/23, 6*x/45, 2*y/24);
		
		backButt.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) 
			{
				
				mainMenu.getContentPane().remove(((BorderLayout) mainMenu.getContentPane().getLayout()).getLayoutComponent(BorderLayout.CENTER));
				PfScheem_All_Tables update= new PfScheem_All_Tables(mainMenu);
				mainMenu.getContentPane().add(update,BorderLayout.CENTER);
				

			}
		});
		return backButt;
	}
	
	public JPanel getRightPanel( final PfPointOfSale salePoint,final Vector<Bon> bon)
	{
		
		
		rightPanel = new JPanel();
		rightPanel.setBackground(new Color(250, 235, 215));
		rightPanel.setLayout(null);
		rightPanel.setBorder(new TitledBorder(null, "קופה", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		rightPanel.setBounds(x*20/48, y/73, x*20/35, y*10/13);
	
		rightPanel.add(getBtnCashFlow(salePoint,bon));
		
	    Icon paymentIcon = new ImageIcon("credit_cards.png");
		Image img = ((ImageIcon) paymentIcon).getImage();
		Image newimg = img.getScaledInstance(50, 40,java.awt.Image.SCALE_SMOOTH);
		paymentIcon = new ImageIcon(newimg);
	    btnIsracart=new JButton("קח מזומנים או אשראי",paymentIcon);
		btnIsracart.setBackground(new Color(200,250,230));
		btnIsracart.setFont(new Font("Tahoma", Font.PLAIN, x/62));
		btnIsracart.setVerticalTextPosition(AbstractButton.BOTTOM);
		btnIsracart.setHorizontalTextPosition(AbstractButton.CENTER);
		btnIsracart.setBounds(x/5, y*2/9, x*3/17, y/10);
		rightPanel.add(btnIsracart);
		
		rightPanel.add(getBtnPresentCard(salePoint,bon));
			       
	    Icon paymentIcon1 = new ImageIcon("tool-tip-hi.png");
		Image img1 = ((ImageIcon) paymentIcon1).getImage();
		Image newimg1 = img1.getScaledInstance(50, 40,java.awt.Image.SCALE_SMOOTH);
		paymentIcon1 = new ImageIcon(newimg1);
	    btnOtherPaymentWay=new JButton("הוסיף טיף",paymentIcon1);
		btnOtherPaymentWay.setBackground(new Color(200,250,230));
		btnOtherPaymentWay.setFont(new Font("Tahoma", Font.PLAIN, x/62));
		btnOtherPaymentWay.setVerticalTextPosition(AbstractButton.BOTTOM);
		btnOtherPaymentWay.setHorizontalTextPosition(AbstractButton.CENTER);
		btnOtherPaymentWay.setBounds(x/5, y*15/32, x*3/17, y/10);
		rightPanel.add(btnOtherPaymentWay);
		rightPanel.add(getDiscount(salePoint,bon));
		return rightPanel;
	}
	
	public JPanel getRightSecondPanel(final PfPointOfSale salePoint,final Vector<Bon> bon)
	{
		rightSecondPanel = new JPanel();
		rightSecondPanel.setBorder(new TitledBorder(null, "קופה", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		rightSecondPanel.setBackground(new Color(250, 235, 215));
		rightSecondPanel.setLayout(null);
		rightSecondPanel.setBounds(x*20/48, y/73, x*20/35, y*10/13);
		
		
		if(totalPriceWithNDSAfterDiscount==0.0)
		{
			final VKForPointOfSale vkbPanel=new VKForPointOfSale(new Color(200,250,230),salePoint,bon,totalPrice,mainMenu,metaDataOrder,wasPaidAlready);
			vkbPanel.setBounds(x/18, y/5, 10*x/21, 3*y/6);
			rightSecondPanel.add(vkbPanel);
		}
		else
		{
			final VKForPointOfSale vkbPanel=new VKForPointOfSale(new Color(200,250,230),salePoint,bon,totalPriceWithNDSAfterDiscount,mainMenu,metaDataOrder,wasPaidAlready);
			vkbPanel.setBounds(x/18, y/5, 10*x/21, 3*y/6);
			rightSecondPanel.add(vkbPanel);
		}
	    textFieldPanel = new JPanel();
	    textFieldPanel.setBackground(new Color(250, 235, 215));
	    textFieldPanel.setLayout(null);
		textFieldPanel.setBounds(x/14, y/50, 12*x/28, y/7);
		flowTextField = new JTextField();
		flowTextField.setBounds(2*x/16, y/28, 3*x/15, y/11);
		flowTextField.setColumns(10);	
		flowTextField.setFont(new Font("Tahoma", Font.PLAIN, x/50));
		textFieldPanel.add(flowTextField);
		rightSecondPanel.add(textFieldPanel);
		
		SwingUtilities.invokeLater(new Runnable(){
		    public void run(){
		    	
		    	flowTextField.grabFocus();
		    }
		});
			
		return rightSecondPanel;
	}
	
	
	
	private JButton getBtnCashFlow(final PfPointOfSale salePoint,final Vector<Bon> bon)
	{
		Icon paymentIcon = new ImageIcon("payment-icon.png");
		Image img = ((ImageIcon) paymentIcon).getImage();
		Image newimg = img.getScaledInstance(50, 40,java.awt.Image.SCALE_SMOOTH);
		paymentIcon = new ImageIcon(newimg);
	    btnCashFlow=new JButton("קח מזומנים או אשראי",paymentIcon);
		btnCashFlow.setBackground(new Color(200,250,230));
		btnCashFlow.setVerticalTextPosition(AbstractButton.BOTTOM);
		btnCashFlow.setHorizontalTextPosition(AbstractButton.CENTER);
		btnCashFlow.setFont(new Font("Tahoma", Font.PLAIN, x/62));
		btnCashFlow.setBounds(x/5, y/11, x*3/17, y/10);
		btnCashFlow.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) 
			{
				salePoint.remove(rightPanel);
				salePoint.add(getRightSecondPanel(salePoint,bon));
				salePoint.repaint();
						
			
			}
		});
		
		return btnCashFlow;
		
	}
	
	private JButton getBtnPresentCard(final PfPointOfSale salePoint,final Vector<Bon> bon)
	{
		
		
		Icon paymentIcon = new ImageIcon("payware_gift-card.png");
		Image img = ((ImageIcon) paymentIcon).getImage();
		Image newimg = img.getScaledInstance(50, 40,java.awt.Image.SCALE_SMOOTH);
		paymentIcon = new ImageIcon(newimg);
	    btnPresentCard=new JButton("הזן מס' כרטיס מתנה",paymentIcon);
		btnPresentCard.setBackground(new Color(200,250,230));
		btnPresentCard.setVerticalTextPosition(AbstractButton.BOTTOM);
		btnPresentCard.setHorizontalTextPosition(AbstractButton.CENTER);
		btnPresentCard.setFont(new Font("Tahoma", Font.PLAIN, x/62));
		btnPresentCard.setBounds(x/5, y*15/43, x*3/17, y/10);
		btnPresentCard.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) 
			{
				salePoint.remove(rightPanel);
				salePoint.add(getRightSecondPresentPanel(salePoint,bon));
				salePoint.repaint();
						
			
			}
		});
		
		return btnPresentCard;
		
	}
	
	private JButton getDiscount(final PfPointOfSale salePoint,final Vector<Bon> bon)
	{
		
		
		Icon paymentIcon = new ImageIcon("discount.png");
		Image img = ((ImageIcon) paymentIcon).getImage();
		Image newimg = img.getScaledInstance(50, 40,java.awt.Image.SCALE_SMOOTH);
		paymentIcon = new ImageIcon(newimg);
	    btnDiscount=new JButton("תן הנחה",paymentIcon);
		btnDiscount.setBackground(new Color(200,250,230));
		btnDiscount.setVerticalTextPosition(AbstractButton.BOTTOM);
		btnDiscount.setHorizontalTextPosition(AbstractButton.CENTER);
		btnDiscount.setFont(new Font("Tahoma", Font.PLAIN, x/62));
		btnDiscount.setBounds(x/5, y*15/25, x*3/17, y/10);
		btnDiscount.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) 
			{
				
				salePoint.remove(rightPanel);
				salePoint.add(getRightSecondDiscountPanel(salePoint,bon));
				salePoint.repaint();
						
			
			}
		});
		
		return btnDiscount;
		
	}
	
	public JPanel getRightSecondPresentPanel(final PfPointOfSale salePoint,final Vector<Bon> bon)
	{
		rightSecondPresentPanel = new JPanel();
		rightSecondPresentPanel.setBorder(new TitledBorder(null, "קופה", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		rightSecondPresentPanel.setBackground(new Color(250, 235, 215));
		rightSecondPresentPanel.setLayout(null);
		rightSecondPresentPanel.setBounds(x*20/48, y/73, x*20/35, y*10/13);
		
		if(totalPriceWithNDSAfterDiscount==0.0)
		{
			final VKForPointOfSalePresentCard vkbPanel=new VKForPointOfSalePresentCard(new Color(200,250,230),salePoint,bon,totalPrice,mainMenu,metaDataOrder);
			vkbPanel.setBounds(x/11, y/4, 8*x/21, 3*y/8);
			rightSecondPresentPanel.add(vkbPanel);
		}
		else
		{
			
			final VKForPointOfSalePresentCard vkbPanel=new VKForPointOfSalePresentCard(new Color(200,250,230),salePoint,bon,totalPriceWithNDSAfterDiscount,mainMenu,metaDataOrder);
			vkbPanel.setBounds(x/11, y/4, 8*x/21, 3*y/8);
			rightSecondPresentPanel.add(vkbPanel);
		}
		
	    textFieldPanel = new JPanel();
	    textFieldPanel.setBackground(new Color(250, 235, 215));
	    textFieldPanel.setLayout(null);
		textFieldPanel.setBounds(x/14, y/50, 12*x/28, y/7);
		flowTextField = new JTextField();
		flowTextField.setFont(new Font("Tahoma", Font.PLAIN, x/50));
		flowTextField.setBounds(2*x/16, y/28, 3*x/15, y/11);
		flowTextField.setColumns(10);
		textFieldPanel.add(flowTextField);
		rightSecondPresentPanel.add(textFieldPanel);
	//	rightSecondPresentPanel.add(vkbPanel);
		rightSecondPresentPanel.add(getCancelButt(salePoint,bon));
		rightSecondPresentPanel.add(createPayButton(salePoint,bon));
		SwingUtilities.invokeLater(new Runnable(){
		    public void run(){
		    	
		    	flowTextField.grabFocus();
		    }
		});
			
		return rightSecondPresentPanel;
	}
	
	public JButton getCancelButt(final PfPointOfSale salePoint,final Vector<Bon> bon)
	{
		Icon cancelIcon = new ImageIcon("cancel.png");
		Image img = ((ImageIcon) cancelIcon).getImage();
		Image newimg = img.getScaledInstance(40, 40,java.awt.Image.SCALE_SMOOTH);
		cancelIcon = new ImageIcon(newimg);
	    cancelButt=new JButton("בטל",cancelIcon);
		cancelButt.setBackground(new Color(200,250,230));
	    cancelButt.setVerticalTextPosition(AbstractButton.BOTTOM);
	    cancelButt.setHorizontalTextPosition(AbstractButton.CENTER);
	    cancelButt.setFont(new Font("Tahoma", Font.BOLD, x/90));
	    cancelButt.setBounds(130, 15*y/23, 6*x/45, 2*y/24);
		
	    cancelButt.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) 
			{
				
				salePoint.remove(rightSecondPresentPanel);
				salePoint.add(getRightPanel(salePoint,bon));
				salePoint.repaint();

			}
		});
		return cancelButt;
	}
	
	
	/*public JButton getCheckButt(final PfPointOfSale salePoint,final Vector<Bon> bon)
	{
		Icon cancelIcon = new ImageIcon("Check.png");
		Image img = ((ImageIcon) cancelIcon).getImage();
		Image newimg = img.getScaledInstance(40, 40,java.awt.Image.SCALE_SMOOTH);
		cancelIcon = new ImageIcon(newimg);
	    checkButt=new JButton("בדוק יתרה",cancelIcon);
	    checkButt.setBackground(new Color(200,250,230));
	    checkButt.setVerticalTextPosition(AbstractButton.BOTTOM);
	    checkButt.setHorizontalTextPosition(AbstractButton.CENTER);
	    checkButt.setFont(new Font("Tahoma", Font.BOLD, x/90));
	    checkButt.setBounds(420, 15*y/23, 6*x/45, 2*y/24);
		
	    checkButt.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) 
			{
				
				salePoint.remove(rightSecondPresentPanel);
				salePoint.add(getRightPanel(salePoint,bon));
				salePoint.repaint();

			}
		});
		return checkButt;
	}*/
	
	private JButton createPayButton(final PfPointOfSale salePoint,final Vector<Bon> bon)
    {
		
		Icon cancelIcon = new ImageIcon("Check.png");
		Image img = ((ImageIcon) cancelIcon).getImage();
		Image newimg = img.getScaledInstance(40, 40,java.awt.Image.SCALE_SMOOTH);
		cancelIcon = new ImageIcon(newimg);
	    payButt=new JButton("שלם",cancelIcon);
	    payButt.setBackground(new Color(200,250,230));
	    payButt.setVerticalTextPosition(AbstractButton.BOTTOM);
	    payButt.setHorizontalTextPosition(AbstractButton.CENTER);
	    payButt.setFont(new Font("Tahoma", Font.BOLD, x/90));
	    payButt.setBounds(420, 15*y/23, 6*x/45, 2*y/24);
	    payButt.addActionListener(new java.awt.event.ActionListener() 
		   {
			public void actionPerformed(java.awt.event.ActionEvent e) 
			{
				try{
					
					Integer f=Integer.parseInt(flowTextField.getText());
											
				}catch(NumberFormatException e1)
				{
					
					JOptionPane.showMessageDialog(null,"סכום לא תקין");
					flowTextField.setText("");
					 return;	
					
				}
				try{
				MessageCheckExistPresentCard msgExist = new MessageCheckExistPresentCard(Integer.parseInt(flowTextField.getText()));
					 mainMenu.ms.client.sendToServer(msgExist);
				MessageCheckExistPresentCardReply result = (MessageCheckExistPresentCardReply)mainMenu.ms.client.GetMessage();	
					 
						if (result.getCheckFlag()==0)
				    	{
							
				    		JOptionPane.showMessageDialog(null,"כרטיס לא קיים או יש בעיה בתקשורת ");
				    		return;
				    	}
				    }
				catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				try {
					  MessageCheckBalancePresentCard msgBalance = new MessageCheckBalancePresentCard(Integer.parseInt(flowTextField.getText()));
					  	  mainMenu.ms.client.sendToServer(msgBalance);
					  MessageCheckBalancePresentCardReply result = (MessageCheckBalancePresentCardReply)mainMenu.ms.client.GetMessage();	
						  balance=result.getBalance();
					  }
					  catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
				if(totalPriceWithNDSAfterDiscount==0.0)
				{}
				else
				{
					totalPrice=	totalPriceWithNDSAfterDiscount;
								
				 if(balance>=totalPrice)
				 {
				
					Date dat = new Date();
					Payment pay = new Payment();
				 			 
				  DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
				  DateFormat df1 = new SimpleDateFormat("HH:mm:ss");
				 
				  String   data = df.format(dat);
				  String   time = df1.format(dat);
				  
				  pay.setDate(data);
				  pay.setTime(time);
				  pay.setTypePayment("כרטיס מתנה");
				  pay.setNumPresentCard(Integer.parseInt(flowTextField.getText()));
				  pay.setNumtable(Integer.parseInt(bon.get(0).getTid()));
				  pay.setOrderid(Integer.parseInt(metaDataOrder.getOrderId()));
				  pay.setAmount(totalPrice);
				  pay.setChange((float) 0);
				  pay.setBalance(balance-totalPrice);
				 
				
				
				  
				 
				  MessageAddNewPaymentOfTable msgPayment= new MessageAddNewPaymentOfTable(pay);
				  try {
					 
						mainMenu.ms.client.sendToServer(msgPayment);
						MessageSavingReply result = (MessageSavingReply)mainMenu.ms.client.GetMessage();
						JOptionPane.showMessageDialog(null,"נשאר כסף : "+pay.getBalance());
						//----------Udalyaem panel s klavoy i vozvrachaem panel s viborom zurat tashlum
						salePoint.remove(salePoint.rightSecondPresentPanel);
					    salePoint.add(salePoint.getRightPanel(salePoint, bon));
					    //---------Pereschitivaem i obnovlyaem levuyu panel
					   
						salePoint.calculatePricesForLefrPanel();
											
				    	if (result.getResult()== '0')
				    	{
				    		JOptionPane.showMessageDialog(null,"בעיית תקשורת 03");
				    	}
				    			    	
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				 }
				
				 else
					 //zdes nado postavit okno iz kotorogo mojno pereyti na zapolnenie katrochki
						JOptionPane.showMessageDialog(null,"אין מספיק כסף ");
				}
			}
			
		});
	    return payButt; 
        
    }
	public JPanel getRightSecondDiscountPanel(final PfPointOfSale salePoint,final Vector<Bon> bon)
	{
		rightSecondDiscountPanel = new JPanel();
		rightSecondDiscountPanel.setBorder(new TitledBorder(null, "קופה", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		rightSecondDiscountPanel.setBackground(new Color(250, 235, 215));
		rightSecondDiscountPanel.setLayout(null);
		rightSecondDiscountPanel.setBounds(x*20/48, y/73, x*20/35, y*10/13);
		final VKForDiscount vkbPanel=new VKForDiscount(new Color(200,250,230),salePoint,bon,totalPrice,mainMenu,metaDataOrder);
		vkbPanel.setBounds(x/11, y/5, 8*x/21, 3*y/6);
	    textFieldPanel = new JPanel();
	    textFieldPanel.setBackground(new Color(250, 235, 215));
	    textFieldPanel.setLayout(null);
		textFieldPanel.setBounds(x/14, y/50, 12*x/28, y/7);
		flowTextField = new JTextField();
		flowTextField.setFont(new Font("Tahoma", Font.PLAIN, x/50));
		flowTextField.setBounds(2*x/16, y/28, 3*x/15, y/11);
		flowTextField.setColumns(10);	
		textFieldPanel.add(flowTextField);
		rightSecondDiscountPanel.add(textFieldPanel);
		rightSecondDiscountPanel.add(vkbPanel);
		SwingUtilities.invokeLater(new Runnable(){
		    public void run(){
		    	
		    	flowTextField.grabFocus();
		    }
		});
			
		return rightSecondDiscountPanel;
	}
	
	
	
	
	//------------------------------------------------------------------------
	private void InitFram() {
		
		
		
		boolean bExit;
		String ESC = ((char) 0x1b) + "";
		String fDate;
		String sBuf;
		String BcData;
   System.out.println("V NACHALE");
   
   
   //--------------------------------------------------------------------------
   
   
		try {
			
			
			
			
			if (mainMenu.getjPos_Printer().getCapRecPresent() == false) {
				JOptionPane
						.showMessageDialog(
								null,
								"This Printer doesn't have the Receipt Station.",
								"Printer", 0);
				return;
			}

			if (mainMenu.getjPos_Printer().getCapRecLeft90() == false) {
				JOptionPane
						.showMessageDialog(
								null,
								"This printer doesn't have a rotation printing function.",
								"Printer", 0);
				return;
			}

			Calendar cal = Calendar.getInstance();
			java.text.SimpleDateFormat sdf = new SimpleDateFormat(
					"yyyy-MM-dd");
			fDate = sdf.format(cal.getTime());
			bExit = false;
			BcData = "123456789012";

			mainMenu.getjPos_Printer().setAsyncMode(true);
			mainMenu.getjPos_Printer().transactionPrint(
					POSPrinterConst.PTR_S_RECEIPT,
					POSPrinterConst.PTR_TP_TRANSACTION);

		} catch (JposException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			JOptionPane.showMessageDialog(null,
					"Can't use a POS Printer.", "Printer", 0);
			return;
		}

		
	//------------------------------------------------------------------------	
		
		
		
		
		
		
		/*try {
			mainMenu.getjPos_Printer().rotatePrint(POSPrinterConst.PTR_S_RECEIPT,
					POSPrinterConst.PTR_RP_LEFT90
							+ POSPrinterConst.PTR_RP_BITMAP
							+ POSPrinterConst.PTR_RP_BARCODE);
		} catch (JposException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}*/

		System.out.println("pered while");
		while (true) {
			//System.out.println("WHILE");
			try {
				//System.out.println("try");
				POSPrinter jPos_Printer=mainMenu.getjPos_Printer();
				jPos_Printer.printNormal(POSPrinterConst.PTR_S_RECEIPT,
						ESC + "|4C" + ESC + "|bC" + "ROBERG\n");
				sBuf = sPace(29);
				jPos_Printer.printNormal(POSPrinterConst.PTR_S_RECEIPT,
						ESC + "|2uC" + sBuf + fDate + "\n");

				jPos_Printer.setRecLineSpacing(mainMenu.getjPos_Printer()
						.getRecLineHeight());
				sBuf = sLine(45);
				jPos_Printer.printNormal(POSPrinterConst.PTR_S_RECEIPT,
						"No order                           Time\n");
				//System.out.println("pered kalendarem");
				Calendar cal = Calendar.getInstance();
				java.text.SimpleDateFormat sdf = new SimpleDateFormat(
						"HH:mm:ss");
				fDate = sdf.format(cal.getTime());
				System.out.println("posle kalendarem");
				jPos_Printer.printNormal(POSPrinterConst.PTR_S_RECEIPT,
						"0013                                 " + fDate
								+ "\n");
				jPos_Printer.printNormal(POSPrinterConst.PTR_S_RECEIPT,
						ESC + "|N" + sBuf + "\n");
				jPos_Printer
						.printNormal(POSPrinterConst.PTR_S_RECEIPT,
								"Antrikot                          28 shakalov\n");
				jPos_Printer
						.printNormal(POSPrinterConst.PTR_S_RECEIPT,
								"Supchik                           12 shakalov\n");
				System.out.println("pered print normal");
				jPos_Printer.printNormal(POSPrinterConst.PTR_S_RECEIPT,
						ESC + "|N" + sBuf + "\n");
				sBuf = "Subtotal                           40 shakalov";
				jPos_Printer.printNormal(POSPrinterConst.PTR_S_RECEIPT,
						sBuf + "\n");
				sBuf = "Grebanniy nalog                1.8 shakalov";
				jPos_Printer.printNormal(POSPrinterConst.PTR_S_RECEIPT,
						sBuf + "\n");
				sBuf = "Total                          41.8 shakalov";
				jPos_Printer.printNormal(POSPrinterConst.PTR_S_RECEIPT,
						ESC + "|bC" + sBuf + "\n");
				sBuf = "Zaplacheno                         50 shakalov";
				jPos_Printer.printNormal(POSPrinterConst.PTR_S_RECEIPT,
						sBuf + "\n");
				sBuf = "Sdacha                             8.2 shakalov";
				jPos_Printer.printNormal(POSPrinterConst.PTR_S_RECEIPT,
						sBuf + "\n");
				sBuf = sLine(45);
				jPos_Printer.printNormal(POSPrinterConst.PTR_S_RECEIPT,
						ESC + "|N" + sBuf + "\n");
				sBuf = "                  SEE YOU AGAIN               ";
				jPos_Printer.printNormal(POSPrinterConst.PTR_S_RECEIPT,
						ESC + "|N" + sBuf + "\n");
				
				System.out.println("PECHAT");
				break;

			} catch (JposException e1) {
				e1.printStackTrace();
				Object[] options = { "Stop", "Retry", "Ignore" };
				int n = JOptionPane.showOptionDialog(null,
						"Fails to output to a printer.\nRetry?",
						"Warning ", JOptionPane.DEFAULT_OPTION,
						JOptionPane.WARNING_MESSAGE, null, options,
						options[0]);
				if (n != 2) {
					try {
						mainMenu.getjPos_Printer().clearOutput();
					} catch (JposException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					}
				}
				if (n == 0) {
					bExit = true;
					return;
				}
				if (n != 1) {
					break;
				}
			}
		}

		try {
			mainMenu.getjPos_Printer().rotatePrint(POSPrinterConst.PTR_S_RECEIPT,
					POSPrinterConst.PTR_RP_NORMAL);
		} catch (JposException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		if (!bExit) {
			try {
				sBuf = String.format("|%dlF", mainMenu.getjPos_Printer()
						.getRecLinesToPaperCut());
				mainMenu.getjPos_Printer().printNormal(POSPrinterConst.PTR_S_RECEIPT,
						ESC + sBuf);
			} catch (JposException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		} else {
			try {
				mainMenu.getjPos_Printer().clearOutput();
			} catch (JposException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
        System.out.println("pered while s dvoykoy");
		while (mainMenu.getjPos_Printer().getState() != 2)
			;
		System.out.println("posle while s dvoykoy");
		try {
			mainMenu.getjPos_Printer().transactionPrint(
					POSPrinterConst.PTR_S_RECEIPT,
					POSPrinterConst.PTR_TP_NORMAL);
			mainMenu.getjPos_Printer().setAsyncMode(false);
			if (mainMenu.getjPos_Printer().getCapRecPapercut() == true) {
				switch (mainMenu.getManagePrinter().getnCut()) {
				case 0:
					mainMenu.getjPos_Printer().cutPaper(50);
					break;
				case 1:
					mainMenu.getjPos_Printer().cutPaper(100);
					break;
				case 2:
					break;
				}
			}
		} catch (JposException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
			}
				
	private String sPace(int iLenth) {
		// TODO Auto-generated method stub
		String sSpace;
		char chSpace[] = new char[iLenth];
		for (int j = 0; j < iLenth; j++) {
			chSpace[j] = (char) 0x20;
		}
		sSpace = new String(chSpace);
		return sSpace;
	}

	private String sLine(int iLenth) {
		String sSpace;
		char chSpace[] = new char[iLenth];
		for (int j = 0; j < iLenth; j++) {
			chSpace[j] = (char) 0x2D;
		}
		sSpace = new String(chSpace);
		return sSpace;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
